package timesheet.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import timesheet.model.Event;
import timesheet.model.Project;
import timesheet.model.Project;

@Repository
@SuppressWarnings("unchecked")
public class ProjectRepository {
	@PersistenceContext
    EntityManager em;
	
	public void createProject(Project a) {
		em.persist(a);
	}
	
	
	public void merge(Project a) {
		em.merge(a);
	}
	
	public void detacheEntity(Project a) {
		em.detach(a);
	}
	
	public Project find(Long id){
		return em.find(Project.class, id);
	}
	
	
	public void remove(Project a){
		em.remove(a);
	}
	
	public List<Project> getAllProject() {
        List<Project> ProjectList = em.createQuery("select p from Project p ORDER BY p.id")
         .getResultList();
        return ProjectList;     
	}
	
	public Project findByName(String name){
		return getSingleOrNullResult(em.createQuery("select p from Project p where p.projectName = :name").setParameter("name", name));
	}
	
	public Project findIdString(String id){
		Long stringid = Long.parseLong(id);
		return em.find(Project.class, stringid);
	}
	
	protected Project getSingleOrNullResult(Query query) {
        try {
            Project result = (Project)query.getSingleResult();
            return result;
        } catch (NoResultException nre) {
            return null;  // Normal, entity is just not found.
        }
    }
}
